package com.bjtang.book.controller;

import java.time.LocalDateTime;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjtang.book.dto.IdDto;
import com.bjtang.book.dto.ReturnDto;
import com.bjtang.book.dto.ShipmentsDto;
import com.bjtang.book.entiy.BookTable;
import com.bjtang.book.myexception.DataCheckException;
import com.bjtang.book.service.BookService;
import com.bjtang.book.service.MyService;
import com.bjtang.book.service.SysUserDtoService;
import com.bjtang.book.util.ReturnUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "图书商品管理")
@Validated
@RestController
@RequestMapping(value = "/book/")
public class BookController {
	@Autowired
	private BookService bookService;
	@Autowired
	private MyService myService;
	@Autowired
	private SysUserDtoService sysUserDtoService;

	@ApiOperation("新建图书商品")
	@PostMapping("/")
	public ReturnDto addBook(@RequestBody @Valid BookTable book) {
		book.setFounder(myService.getMyselfId());
		return ReturnUtil.successOrError(bookService.save(book));
	}

	@ApiOperation("删除图书商品")
	@DeleteMapping("/")
	public ReturnDto deleteBookById(@RequestBody @Valid IdDto bookId) {
		checkBook(bookId.getId(), "check");
		return ReturnUtil.successOrError(bookService.removeById(bookId.getId()), bookId.getId());
	}

	@ApiOperation("编辑图书商品")
	@PutMapping("/")
	public ReturnDto updateBookById(@RequestBody @Valid BookTable book) {
		checkBook(book.getBookNumber(), "check");
		return ReturnUtil.successOrError(bookService.saveOrUpdate(book));
	}

	@ApiOperation("查询某订单收货人地址")
	@GetMapping("/by-buyer/{bookId}")
	public ReturnDto GetBuyerById(@PathVariable Long bookId) {
		BookTable checkBook = checkBook(bookId, "buyer");
		return ReturnUtil.success(sysUserDtoService.selectUserAddressById(checkBook.getBuyerNumber()));
	}

	@ApiOperation("查询单个图书商品")
	@GetMapping("/by-book/{bookId}")
	public ReturnDto GetBookById(@PathVariable Long bookId) {
		return ReturnUtil.success(bookService.getById(bookId));
	}

	@ApiOperation("查询商品列表ByMyPage")
	@GetMapping("/by-user/{bookIs}/{current}/{size}")
	public ReturnDto GetArticleByUserPage(@PathVariable Long bookIs, @PathVariable Long current,
			@PathVariable Long size) {
		Page<BookTable> page = new Page<BookTable>(current, size);
		// 创建状态的
		if (bookIs.longValue() == 0)
			return ReturnUtil.success(bookService.lambdaQuery().eq(BookTable::getFounder, myService.getMyselfId())
					.eq(BookTable::getStatus, 0).orderByDesc(BookTable::getBookNumber).page(page));
		// 我买到的
		if (bookIs.longValue() == 1)
			return ReturnUtil.success(bookService.lambdaQuery().eq(BookTable::getBuyerNumber, myService.getMyselfId())
					.orderByDesc(BookTable::getBookNumber).page(page));
		// 我卖出的
		if (bookIs.longValue() == 2)
			return ReturnUtil.success(bookService.lambdaQuery().eq(BookTable::getFounder, myService.getMyselfId())
					.gt(BookTable::getBuyerNumber, 0).orderByDesc(BookTable::getBookNumber).page(page));
		return ReturnUtil.error(400, "参数有误,bookIs应该为0-2之间");
	}

	@ApiOperation("购买图书商品")
	@PutMapping("/buy/")
	public ReturnDto BuyBookById(@RequestBody IdDto bookId) {
		checkBook(bookId.getId(), "buy");
		BookTable book = new BookTable();
		book.setBookNumber(bookId.getId());
		book.setStatus(1);
		book.setBuyerNumber(myService.getMyselfId());
		book.setBuyerTime(LocalDateTime.now());
		return ReturnUtil.successOrError(bookService.saveOrUpdate(book));
	}

	@ApiOperation("发货图书商品")
	@PutMapping("/shipments/")
	public ReturnDto ShipmentsBookById(@RequestBody ShipmentsDto shipmentsDto) {
		checkBook(shipmentsDto.getId(), "shipments");
		BookTable book = new BookTable();
		book.setBookNumber(shipmentsDto.getId());
		book.setStatus(2);
		book.setTrackingNumber(shipmentsDto.getTrackingNumber());
		return ReturnUtil.successOrError(bookService.saveOrUpdate(book));
	}

	@ApiOperation("确认收货图书商品")
	@PutMapping("/receipt/")
	public ReturnDto ReceiptBookById(@RequestBody IdDto bookId) {
		checkBook(bookId.getId(), "receipt");
		BookTable book = new BookTable();
		book.setBookNumber(bookId.getId());
		book.setStatus(3);
		return ReturnUtil.successOrError(bookService.saveOrUpdate(book));
	}

	@ApiOperation("取消购买图书商品")
	@PutMapping("/cancel/")
	public ReturnDto CancelBookById(@RequestBody IdDto bookId) {
		checkBook(bookId.getId(), "cancel");
		BookTable book = new BookTable();
		book.setBookNumber(bookId.getId());
		book.setStatus(4);
		return ReturnUtil.successOrError(bookService.saveOrUpdate(book));
	}

	// 权限校验
	BookTable checkBook(Long bookId, String size) {
		// 图书状态0创建中 1已被购买 2发货中 3交易成功 4.取消订单
		BookTable byId = bookService.getById(bookId);
		if (byId == null)
			throw new DataCheckException("图书商品没找到");

		if ("check".equals(size)) {
			if (byId.getFounder().longValue() != myService.getMyselfId().longValue())
				throw new DataCheckException("没有操作权限");
			if (byId.getStatus() > 0)
				throw new DataCheckException("图书商品不在创建中");
		}
		// 购买检查
		if ("buy".equals(size)) {
			if (byId.getStatus() > 0)
				throw new DataCheckException("图书商品不在创建中");
		}
		// 发货检查
		if ("shipments".equals(size)) {
			if (byId.getFounder().longValue() != myService.getMyselfId().longValue())
				throw new DataCheckException("没有操作权限");
			if (byId.getStatus() != 1)
				throw new DataCheckException("图书商品不在被购买状态中");
		}
		// 确认收货检查
		if ("receipt".equals(size)) {
			if (byId.getBuyerNumber().longValue() != myService.getMyselfId().longValue())
				throw new DataCheckException("没有操作权限");
			if (byId.getStatus() != 2)
				throw new DataCheckException("图书商品不在发货状态中");
		}
		// 取消订单检查
		if ("cancel".equals(size)) {
			if (byId.getBuyerNumber().longValue() != myService.getMyselfId().longValue()
					|| byId.getFounder().longValue() != myService.getMyselfId().longValue())
				throw new DataCheckException("没有操作权限");
			if (byId.getStatus() != 0 && byId.getStatus() != 1)
				throw new DataCheckException("图书商品目前状态不支持取消,请检查是否已经发货/收货/取消");
		}

		// 收货人地址获取检查
		if ("buyer".equals(size)) {
			if (byId.getFounder().longValue() != myService.getMyselfId().longValue())
				throw new DataCheckException("没有操作权限");
			if (byId.getStatus() != 1 && byId.getStatus() != 2)
				throw new DataCheckException("图书商品只有在被购买和发货中才能看到收货地址");
		}
		return byId;
	}
}
